package com.shujia.day19.mysql.pool;

import java.sql.SQLException;

public class MysqlConPoolManager {
    // TODO 用于管理Mysql连接池的类，可以创建一个连接池 将配置信息和连接池对象进行配置
    private static MySqlConnectionPool mySqlConnectionPool = null;

    public static MySqlConnectionPool createMysqlConPool(String propertiesPath) throws Exception {
        MysqlPoolConfig mysqlPoolConfig = new MysqlPoolConfig(propertiesPath);
        mySqlConnectionPool = new MySqlConnectionPool(mysqlPoolConfig);
        new MysqlTimerCheck(mySqlConnectionPool);
        return mySqlConnectionPool;
    }

    public static MysqlConnection getOneCon() {
        return mySqlConnectionPool.getMysqlCon();
    }

    public static void releaseMysqlCon(MysqlConnection mysqlConnection) {
        mySqlConnectionPool.releaseMysqlCon(mysqlConnection);
    }

    public static void closeConPool() {
        if (mySqlConnectionPool != null) {
            for (MysqlConnection mysqlConnection : mySqlConnectionPool.notUseCon) {
                try {
                    mysqlConnection.connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            for (MysqlConnection mysqlConnection : mySqlConnectionPool.usingCon) {
                try {
                    mysqlConnection.connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
